from absl import app

import datetime
import os

import pandas

import glob

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

from dominate import document
from dominate.tags import *
import jinja2
from flask import request

import re

import coin.research.read_strat_info as rsi

from flask import Flask, render_template, Markup

def get_imgfilepaths(daily_or_weekly, root_path, yyyymmdd, strat_group, strat_name, days=None):
  if yyyymmdd.find("W") >= 0:
    trading_date = datetime.datetime.strptime(yyyymmdd + '-1', "%YW%W-%w")
    trading_date += datetime.timedelta(days=7)
  else:
    trading_date = datetime.datetime.strptime(yyyymmdd, "%Y%m%d")

  if (daily_or_weekly.find('day') >= 0 or daily_or_weekly in
          ["merged", "each", "merged_usefeed", "each_usefeed", "matchsim"]):
    if daily_or_weekly == "matchsim":
      nday = 5
    else:
      nday = days or int(daily_or_weekly.split("day")[0])
      nday = int(nday)
    fromymd = (trading_date - datetime.timedelta(days=nday)).strftime("%Y%m%d")
    toymd = (trading_date - datetime.timedelta(days=1)).strftime("%Y%m%d")
    if daily_or_weekly == "matchsim":
      tdstr = f"{fromymd}_{toymd}"
      findpath = os.path.join(root_path, tdstr)
    else:
      tdstr = f"{fromymd}-{toymd}"
      if daily_or_weekly.find("merged") >= 0:
        subdir = "merged"
      else:
        subdir = "each"
      findpath = os.path.join(root_path, tdstr, subdir)
    print(findpath)
    imgfilepaths = []
    for root, _, imgfiles in os.walk(findpath):
      for imgfile in imgfiles:
        if strat_name is not None:
          if not re.match(strat_name, imgfile):
            continue
        if imgfile.endswith(".png"):
          imgfilepaths.append((imgfile.split('/')[-1], os.path.join(root, imgfile)))
    imgfilepaths = sorted(imgfilepaths)
    imgfilepaths = [
        f"http://10.21.1.28:8080{imgfilepath}" for _, imgfilepath in imgfilepaths
    ]
    return imgfilepaths

  print(daily_or_weekly, yyyymmdd, strat_group, strat_name)

  if trading_date.date() == datetime.datetime.today().date():
    trading_date -= datetime.timedelta(days=1)

  print(trading_date, strat_group, strat_name)

  strats = rsi.get_strategy_info(
      trading_date=trading_date, strategy_group=strat_group, strategy_name=strat_name)
  if len(strats) == 0:
    strats = rsi.get_strategy_info(
        trading_date=trading_date-datetime.timedelta(days=1), strategy_group=strat_group, strategy_name=strat_name)

  stratnames = list(set([strat['strategy_name'] for strat in strats]))
  print(stratnames)

  selstrats = [stratname.split("/")[-1] for stratname in stratnames]

  if strat_name is not None:
    patt = re.compile(strat_name)
    selstrats = [stratname for stratname in selstrats if patt.match(stratname) is not None]

  imgfilepaths = []
  daily_or_weekly_dir = daily_or_weekly.replace("daily_sim", "daily")
  for selstrat in selstrats:
    for root, _, imgfiles in os.walk(f"{root_path}/{daily_or_weekly_dir}/{yyyymmdd}/{selstrat}"):
      for imgfile in imgfiles:
        if imgfile.endswith(".png"):
          imgfilepaths.append((imgfile.split('/')[-1], os.path.join(root, imgfile)))
  par_path = "/remote/iosg/strat-1/buckets/analysis.derived.coin/live/plot"
  imgfilepaths = sorted(imgfilepaths)
  livesim = 'sim' if daily_or_weekly in ['daily_sim'] else 'live'
  imgfilepaths = [
      imgfilepath.replace(par_path, f"http://10.21.104.33:8000/{livesim}") for _, imgfilepath in imgfilepaths
  ]
  return imgfilepaths


def get_trading_dates(trading_date_str):
  if trading_date_str.find("-") >= 0:
    tdfrom, tdto = trading_date_str.split("-")
    return pandas.date_range(tdfrom, tdto).to_pydatetime()
  else:
    return [datetime.datetime.strptime(trading_date_str, '%Y%m%d')]


exurls=[
"http://10.21.1.21:5000/daily?strat_group=lm-agg2",
"http://10.21.1.21:5000/daily?strat_group=lm-pass2",
"http://10.21.1.21:5000/daily?strat_group=basis_smm2",
"http://10.21.1.21:5000/daily?strat_group=interval",
"http://10.21.1.21:5000/daily?strat_name=.*huobi.*",
"http://10.21.1.21:5000/order_plot?strat_name=interval.*",
"http://10.21.1.21:5000/daily_sim?strat_group=lm-agg2",
"http://10.21.1.21:5000/weekly?strat_group=lm-agg2",
"http://10.21.1.21:5000/weekly?strat_group=lm-agg2&date=2020W10",
"http://10.21.1.21:5000/daily?strat_group=interval&date=20200601",
"http://10.21.1.21:5000/merged?days=20&strat_name=.*lm.*",
"http://10.21.1.21:5000/each?days=20&strat_name=.*lm.*",
"http://10.21.1.21:5000/merged?days=10&strat_name=.*lm.*",
"http://10.21.1.21:5000/each?days=10&strat_name=.*lm.*",
"http://10.21.1.21:5000/merged?days=5&strat_name=.*lm.*",
"http://10.21.1.21:5000/each?days=5&strat_name=.*lm.*",
"http://10.21.1.21:5000/merged_usefeed?days=5&strat_name=.*lm.*",
"http://10.21.1.21:5000/each_usefeed?days=5&strat_name=.*lm.*",
"http://10.21.1.21:5000/matchsim",
"http://10.21.1.21:5000/live_pnl",
"http://10.21.1.21:5000/live_pnl?strat_group=lm-agg2",
"http://10.21.1.21:5000/live_pnl?strat_name=lm_focus.*",
"http://10.21.1.21:5000/live_pnl?trader=jhkim",
"http://10.21.1.21:5000/live_pnl_symbol?strat_group=lm-agg2",
"http://10.21.1.21:5000/live_pnl_symbol?strat_name=lm_focus.*",
"http://10.21.1.21:5000/live_pnl_symbol?trader=jhkim",
"http://10.21.1.21:5000/live_pnl_symbol?strat_name=lm_.*&symbol=DOGE.*",
]


def render_live_pnl(strat_group, strat_name, trader, symbol=None):
  from importlib.machinery import SourceFileLoader
  plpnl = SourceFileLoader(
      "plpnl", "./python/coin_deploy/lm_search/apply/print_live_pnl.py").load_module()

  def callback_hyperlink(dfret):
    format_str = "<a href='http://10.21.1.21:5000/daily?strat_name={strategy_name}'>daily</a>"
    if 'symbol' in dfret:
      format_str += (
          " <a href='http://10.21.1.21:5000/each?days=5&strat_name=.*{strategy_name}.*{symbol}.*'>days5</a>  {strategy_name}")
    else:
      format_str += (
          " <a href='http://10.21.1.21:5000/merged?days=5&strat_name=.*{strategy_name}'>days5</a>  {strategy_name}")
    dfret['strategy_name'] = [format_str.format(**r) for i, r in dfret.iterrows()]
    return dfret

  pnlstr = plpnl.get_live_pnl_html(
      strat_group=strat_group,
      strat_name=strat_name,
      trader=trader,
      callback=callback_hyperlink,
      symbol=symbol)
  return render_template('live_pnl.html',
                          title='Live Pnls',
                          pnlstr=Markup(pnlstr),
                          request=request,
                          exurls=exurls)


def main(_):
  fapp = Flask(__name__, template_folder=".", static_folder='./static')

  @fapp.route('/')
  @fapp.route('/index')
  def index():
    return render_template('index.html',
                           title='Strategy Plots',
                           request=request, exurls=exurls)

  def strat(otype, request):
    args = request.args
    strat_group = args.get('strat_group', None)
    strat_name = args.get('strat_name', None)
    trader = args.get('trader', None)
    if otype == 'live_pnl':
      return render_live_pnl(
          strat_group=strat_group,
          strat_name=strat_name,
          trader=trader)
    elif otype == 'live_pnl_symbol':
      symbol = args.get('symbol', True)
      return render_live_pnl(
          symbol=symbol,
          strat_group=strat_group,
          strat_name=strat_name,
          trader=trader)
    datestr = args.get('date', None)
    days = args.get('days', None)

    if otype in ['daily', 'weekly', 'daily_sim']:
      root_path = "/remote/iosg/strat-1/buckets/analysis.derived.coin/live/plot/pnl_plot"
    elif otype.find('matchsim') >= 0:
      root_path = "/remote/iosg/home/public/plot_share"
    elif otype.find('day') >= 0 or otype in ["merged", "each"]:
      root_path = "/remote/iosg/strat-1/buckets/analysis.derived.coin/live/plot/pplot"
    elif otype in ["merged_usefeed", "each_usefeed"]:
      root_path = "/remote/iosg/strat-1/buckets/analysis.derived.coin/live/plot/pplot_usefeed"
    else:
      root_path = "/remote/iosg/strat-1/buckets/analysis.derived.coin/live/plot/order_plot"

    if otype in ['daily', 'order_plot']:
      if datestr is None:
        dts = [datetime.datetime.now()]
      else:
        dts = get_trading_dates(datestr)
      dtstrs = [dt.strftime("%Y%m%d") for dt in dts]
      daily_or_weekly = 'daily'
    elif otype.find('day') >= 0 or otype in ["matchsim", "merged", "each", "merged_usefeed", "each_usefeed"]:
      daily_or_weekly = otype
      if datestr is None:
        dts = [datetime.datetime.now()]
      else:
        dts = get_trading_dates(datestr)
      dtstrs = [dt.strftime("%Y%m%d") for dt in dts]
    elif otype in ['daily_sim']:
      if datestr is None:
        dts = [datetime.datetime.today() - datetime.timedelta(days=1)]
      else:
        dts = get_trading_dates(datestr)
      daily_or_weekly = 'daily_sim'
      dtstrs = [dt.strftime("%Y%m%d") for dt in dts]
      print(dtstrs)
    elif otype == 'weekly':
      daily_or_weekly = 'weekly'
      if datestr is None:
        datestr = max(os.listdir("/remote/iosg/strat-1/buckets/analysis.derived.coin/live/plot/pnl_plot/weekly"))
      dtstrs = [datestr]

    image_filepaths = []
    for dtstr in dtstrs:
      image_filepaths.extend(
          get_imgfilepaths(daily_or_weekly, root_path, dtstr, strat_group, strat_name, days))
    image_names = [image_path.split("/")[-1] for image_path in image_filepaths]
    #print(image_filepaths)
    return render_template('images.html',
                           title='',
                           image_filepaths=image_filepaths,
                           image_names=image_names)

  @fapp.route('/live_pnl')
  def live_pnl():
    return strat(otype='live_pnl', request=request)

  @fapp.route('/live_pnl_symbol')
  def live_pnl_symbol():
    return strat(otype='live_pnl_symbol', request=request)

  @fapp.route('/5day')
  def day5():
    return strat(otype='5day', request=request)

  @fapp.route('/5day_merged')
  def day5_merged():
    return strat(otype='5day_merged', request=request)

  @fapp.route('/merged')
  def day_merged():
    return strat(otype='merged', request=request)

  @fapp.route('/each')
  def day_each():
    return strat(otype='each', request=request)

  @fapp.route('/merged_usefeed')
  def day_merged_uf():
    return strat(otype='merged_usefeed', request=request)

  @fapp.route('/each_usefeed')
  def day_each_uf():
    return strat(otype='each_usefeed', request=request)

  @fapp.route('/matchsim')
  def matchsim():
    return strat(otype='matchsim', request=request)

  @fapp.route('/weekly')
  def weekly():
    return strat(otype='weekly', request=request)

  @fapp.route('/daily')
  def daily():
    return strat(otype='daily', request=request)

  @fapp.route('/order_plot')
  def order_plot():
    return strat(otype='order_plot', request=request)

  @fapp.route('/daily_sim')
  def daily_sim():
    return strat(otype='daily_sim', request=request)

  fapp.run(host='0.0.0.0', debug=True)
  return


if __name__ == "__main__":
  app.run(main)
